//
//  PKCustomImageTitleButton.swift
//  GoAbroad
//
//  Created by Pink Snow on 2025/5/14.
//

import Foundation
import UIKit

class PKCustomImageTitleButton : UIButton {
    
    // 图片尺寸
    var imageSize: CGSize = CGSize(width: 24, height: 24) {
        didSet {
            setNeedsLayout()
        }
    }
    
    // 图片偏移
    var imageOffset: CGPoint = .zero {
        didSet {
            setNeedsLayout()
        }
    }
    
    // 标题偏移
    var titleOffset: CGPoint = .zero {
        didSet {
            setNeedsLayout()
        }
    }
    
    // 图片和文字的间距
    var spacing: CGFloat = 8 {
        didSet {
            setNeedsLayout()
        }
    }
    
    // 标题字体大小
    override var titleLabel: UILabel? {
        let label = super.titleLabel
        label?.font = titleFont
        return label
    }

    var titleFont: UIFont = UIFont.systemFont(ofSize: 16) {
        didSet {
            titleLabel?.font = titleFont
            setNeedsLayout()
        }
    }

    override func layoutSubviews() {
        super.layoutSubviews()

        guard let imageView = imageView, let titleLabel = titleLabel else {
            return
        }

        // 设置图片大小
        imageView.frame = CGRect(origin: .zero, size: imageSize)
        
        // 设置标题大小
        titleLabel.sizeToFit()
        let titleSize = titleLabel.frame.size
        
        // 计算总宽度
        let totalWidth = imageSize.width + spacing + titleSize.width

        // 起始 X
        let startX = (bounds.width - totalWidth) / 2

        // 图片位置
        imageView.frame = CGRect(
            x: startX + imageOffset.x,
            y: (bounds.height - imageSize.height) / 2 + imageOffset.y,
            width: imageSize.width,
            height: imageSize.height
        )

        // 标题位置
        titleLabel.frame = CGRect(
            x: imageView.frame.maxX + spacing + titleOffset.x,
            y: (bounds.height - titleSize.height) / 2 + titleOffset.y,
            width: titleSize.width,
            height: titleSize.height
        )
    }
}
